import android.annotation.TargetApi;
import android.os.Build;

import javax.crypto.Cipher;
import java.security.*;
import java.security.interfaces.RSAPrivateKey;
import java.security.interfaces.RSAPublicKey;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;
import java.util.Base64;
import java.util.HashMap;
import java.util.Map;

/**
 * Java RSA 加密工具类
 * 参考： https://blog.csdn.net/qy20115549/article/details/83105736
 */
public class RSAUtils4APP {

    /**
     * 密钥长度 于原文长度对应 以及越长速度越慢
     */
    private final static int KEY_SIZE = 1024;
    private final static String publicKeyString = "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCdFesb/CC6KLDra6rbrmlKBKhDjnJog6XkYTGrmZlAQxzos4QPkqG5fnjWboY37rGEDnHG09lLTA94CWdCAxxKH9EBA5wB5cU1DN8LOEwG6PT1hgNK54FD7Kz7Lb2l+Xbut67DW0hXar/nXl9Tt9mraIbfEsdZ+idct83bmPhZzwIDAQAB";


    /**
     * RSA公钥加密
     *
     * @param str       加密字符串
     * @param publicKey 公钥
     * @return 密文
     * @throws Exception 加密过程中的异常信息
     */
    @TargetApi(Build.VERSION_CODES.O)
    public static String encrypt(String str, String publicKey) throws Exception {
        //base64编码的公钥
        byte[] decoded = Base64.getDecoder().decode(publicKey);
        RSAPublicKey pubKey = (RSAPublicKey) KeyFactory.getInstance("RSA").generatePublic(new X509EncodedKeySpec(decoded));
        //RSA加密
        Cipher cipher = Cipher.getInstance("RSA");
        cipher.init(Cipher.ENCRYPT_MODE, pubKey);
        String outStr = Base64.getEncoder().encodeToString(cipher.doFinal(str.getBytes("UTF-8")));
        return outStr;
    }

    public static void main(String[] args) throws Exception {
        String message = "哈哈";
        System.out.println("原文:" + message);

//        String messageEn = encrypt(message, publicKeyString);
        String key = "MIGeMA0GCSqGSIb3DQEBAQUAA4GMADCBiAKBgE5gW7ypyFTgP5smFu/P6VgfTXhuC4Xd/XlvFC2htc/ifcxgHSdCmqYo1mZLzBvyYWV0pU3IRgDdgGCpSuPqBD1U3MQ+bD3Gw+qemNvOislWdBl14q5JShYsOl8tB7evYQazRPg54XPtFA4RQcPSnmi8ZN993E263xJCd5HrmAOPAgMBAAE=";
        String messageEn = encrypt(message, key);
        System.out.println("密文:" + messageEn);

    }
}